#include "FileStreamCharPersist.h"

#include <fstream>
#include <iostream>

FileStreamCharPersist::FileStreamCharPersist(const std::string & filePath)
: filePath(filePath)
, io(nullptr)
{
}
FileStreamCharPersist::~FileStreamCharPersist(){
    close();
}

const long long FileStreamCharPersist::readLongLong() const{
    if(io->good()){
        long long result = -1;
        return (*io >> result) ? result : 10001;
    }
    else{
        std::cout << "read file failed" << std::endl;
        return -1;
    }
}
void FileStreamCharPersist::writeLongLong(const long long seqNo){
    if(io->good()){
        *io << seqNo;
    }
    else{
        std::cout << "write file failed" << std::endl;
    }
}

void FileStreamCharPersist::open() const{
    if(io == nullptr){
        std::fstream * fs = new std::fstream;
        fs->open(filePath, std::ios::binary|std::ios::in|std::ios::out);
        if(!fs->is_open()){
            fs->open(filePath, std::ios::out); 
            fs->close();

            fs->open(filePath, std::ios::binary|std::ios::in|std::ios::out);
        }
        io = fs;
    }
}
void FileStreamCharPersist::close() const{
    if(io != nullptr){
        ((std::fstream*)io)->close();
        delete io;
        io = nullptr;
    }
}
void FileStreamCharPersist::flush(){
    if(io != nullptr){
        io->flush();
    }
}
